/*
 * Created on Dec 24, 2003
 *
 * Local Projects Database
 * Copyright (c) 2003 by eRomania Gateway
 */
package ro.gateway.aida.struts.action;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.Country;
import ro.gateway.aida.obj.OrgType;
import ro.gateway.aida.obj.Organization;
import ro.gateway.aida.obj.Person;
import ro.gateway.aida.obj.db.CountryDB;
import ro.gateway.aida.obj.db.OrgTypeDB;
import ro.gateway.aida.obj.db.OrganizationDB;
import ro.gateway.aida.struts.MultiTilesAction;
import ro.gateway.aida.struts.form.EditOrgForm;
import ro.gateway.aida.usr.Arbiter;
import ro.gateway.aida.usr.Perms;
import ro.gateway.aida.usr.UserUtils;
import ro.gateway.aida.utils.Utils;
import ro.xblue.translator.TranslatorUtils;


/**
 * @author Mihai Postelnicu<p>
 *
 *  e-mail (mihai@ro-gateway.org)<br>
 * (c) 2003 by eRomania Gateway<p>
 * Edits organization data. This is the struts version of the org form
 * @see EditOrganizationServlet.java
 */
public class EditOrgAction extends MultiTilesAction {
    private OrganizationDB orgdb;
    private OrgTypeDB otdb;
    private CountryDB ocdb;
    private Arbiter ar;

    public ActionForward modePrepare(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();
        PersistenceToken token = PersistenceManager.tokenLookup(sc);
        orgdb = OrganizationDB.getManager(token);
        otdb = OrgTypeDB.getManager(token);
        ocdb = CountryDB.getManager(token);
        ar = Arbiter.getManager(token);

        if (UserUtils.getLogged(request, response) == null)
            return mapping.findForward("plslogin");

        if (!ar.canDo(request, Perms.OBJECT_SUBMIT))
            mapping.findForward("norights");

        HttpSession session = request.getSession();
        Object countries = session.getAttribute(Country.LIST);

        if (countries == null) {
            countries = ocdb.getCountries();
            session.setAttribute(Country.LIST, countries);
        }

        Object orgtypes = Utils.getLocalisedSessionObj(session, OrgType.LIST,
                lang);

        if (orgtypes == null) {
            orgtypes = otdb.getAllLocalized(lang);
            session.setAttribute(OrgType.LIST, orgtypes);
        }

        return modeSelect(mapping, form, request, response);
    }

    public ActionForward modeSelect(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HttpSession session = request.getSession();

        if (session.getAttribute(Person.SELECTED) != null)
            return modeAddPerson(mapping, form, request, response);

        if (request.getParameter("unlink_people") != null)
            return modeUnlinkPeople(mapping, form, request, response);

        if (request.getParameter("confirm_save") != null)
            return modeConfirm(mapping, form, request, response);

        if (request.getParameter("confirm_delete") != null)
            return modeConfirm(mapping, form, request, response);

        if (request.getParameter("save") != null)
            return modeSave(mapping, form, request, response);

        if (request.getParameter("delete") != null)
            return modeDelete(mapping, form, request, response);

        if (request.getParameter("back") != null)
            return modeNew(mapping, form, request, response);

        if (request.getParameter("orgid") != null)
            return modeEdit(mapping, form, request, response);

        return modeNew(mapping, form, request, response);
    }

    protected ActionForward modeEdit(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();

        if (request.getParameter("orgid") != null) {
            long orgid = Long.parseLong(request.getParameter("orgid"));
            EditOrgForm eof = (EditOrgForm) form;
            HttpSession session = request.getSession();
            Organization o = (Organization) orgdb.getByID(orgid);

            if (o == null)
                return mapping.findForward("notfound");

			o.setViewLang(lang);
            eof.setAcronym(o.getAcronym());
            eof.setId(o.getId());
            eof.setAddress1(o.getAddress1());
            eof.setAddress2(o.getAddress2());
            eof.setAIDAOrg(o.getAIDAOrg());
            eof.setType(o.getCatID());
            eof.setContactEmail(o.getContactEmail());
            eof.setContactName(o.getContactName());
            
            eof.setContactFax1(o.getContactFax(1));
            eof.setContactFax2(o.getContactFax(2));
            eof.setContactFax3(o.getContactFax(3));
            
            eof.setContactPhone1(o.getContactPhone(1));
            eof.setContactPhone2(o.getContactPhone(2));
            eof.setContactPhone3(o.getContactPhone(3));
            eof.setContactURL(o.getContactURL());
            eof.setContactTitle(o.getContactTitle());
            eof.setName(o.getName().toString());
            eof.setDescription(o.getDescription().toString());
            eof.setCountryISO3(o.getCountryISO3());
            eof.setInfoSource(o.getInfoSource());
            session.setAttribute(Organization.PEOPLE,o.getPersons());
        } else

            return mapping.findForward("fail");

        return mapping.getInputForward();
    }

    protected ActionForward modeNew(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();

        if (request.getParameter("back") != null) {
            EditOrgForm eof = (EditOrgForm) form;
            HttpSession session = request.getSession();
            Organization o = (Organization) session.getAttribute(Organization.EDIT_TAG);
            
            if (o == null)
                return mapping.findForward("plslogin");

			o.setViewLang(lang);
            eof.setAcronym(o.getAcronym());
            eof.setAddress1(o.getAddress1());
            eof.setAddress2(o.getAddress2());
            eof.setAIDAOrg(o.getAIDAOrg());
            eof.setType(o.getCatID());
            eof.setContactEmail(o.getContactEmail());
            eof.setContactName(o.getContactName());
            
            eof.setContactFax1(o.getContactFax(1));
            eof.setContactFax2(o.getContactFax(2));
            eof.setContactFax3(o.getContactFax(3));
            
            
            eof.setContactPhone1(o.getContactPhone(1));
            eof.setContactPhone2(o.getContactPhone(2));
            eof.setContactPhone3(o.getContactPhone(3));
            eof.setContactTitle(o.getContactTitle());
            eof.setContactURL(o.getContactURL());
            eof.setName(o.getName().toString());
            eof.setDescription(o.getDescription().toString());
            eof.setCountryISO3(o.getCountryISO3());
            eof.setInfoSource(o.getInfoSource());
        }

        return mapping.getInputForward();
    }

    protected ActionForward modeConfirm(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();
        HttpSession session = request.getSession();
        
        
        EditOrgForm eof = (EditOrgForm) form;
        long existentId=orgdb.checkExistentAIDAId(eof.getAIDAOrg());
        if(eof.getAIDAOrg()==null || eof.getAIDAOrg().length()<4 || (existentId!=0 && existentId !=eof.getId()) ) {
        	
        	request.setAttribute("error.aidaorg","present");
        	return mapping.getInputForward();
        }
            
        Organization o = new Organization();
		o.setId(eof.getId());
        o.setAcronym(eof.getAcronym());
        o.setAddress1(eof.getAddress1());
        o.setAddress2(eof.getAddress2());
        if(eof.getAIDAOrg()!=null) o.setAIDAOrg(eof.getAIDAOrg().toUpperCase()); else o.setAIDAOrg(null);
        o.setCatID(eof.getType());
        o.setContactEmail(eof.getContactEmail());
      
        o.setContactFax(eof.getContactFax1()+"#"+eof.getContactFax2()+"#"+eof.getContactFax3());
        o.setContactName(eof.getContactName());
        o.setContactPhone(eof.getContactPhone1()+"#"+eof.getContactPhone2()+"#"+eof.getContactPhone3());
        o.setContactURL(eof.getContactURL());
        o.getName().setString(lang, eof.getName());
        o.getDescription().setString(lang, eof.getDescription());
        o.setType(otdb.getById(o.getCatID()));
        o.setCountry(ocdb.getByISO3(eof.getCountryISO3()));
        o.setCountryISO3(eof.getCountryISO3());
        o.setUserID(UserUtils.getLogged(request, response).getId());
        o.setPersons((List)session.getAttribute(Organization.PEOPLE));
        o.setInfoSource(eof.getInfoSource());
        o.setContactTitle(eof.getContactTitle());
        o.setViewLang(lang);
       
        session.setAttribute(Organization.EDIT_TAG, o);

        if (request.getParameter("confirm_save") != null)
            request.setAttribute("confirm_save", "");

        if (request.getParameter("confirm_delete") != null)
            request.setAttribute("confirm_delete", "");

        o.setViewLang(lang);

        //redirect to confirmation page
        return mapping.findForward("confirm");
    }

    protected ActionForward modeSave(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();

        HttpSession session = request.getSession();
        Organization o = (Organization) session.getAttribute(Organization.EDIT_TAG);

        if (o == null)
            return mapping.findForward("plslogin");

        if ((o.getId() != -1) &&
                !ar.canDo(request, Perms.OBJECT_SUBMIT, o.getId(),
                    Arbiter.ORG_TYPE))
            return mapping.findForward("norights");

        o.setViewLang(lang);

        if (o.getId() == -1)
            orgdb.insert(o, lang);
        else
            orgdb.update(o, lang);

        request.setAttribute("operation", "'organization save'");

        return mapping.findForward("success");
    }

    protected ActionForward modeAddPerson(ActionMapping mapping,
        ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        EditOrgForm eof = (EditOrgForm) form;
        Person p = (Person) session.getAttribute(Person.SELECTED);
        List people=(List)session.getAttribute(Organization.PEOPLE);
        people.add(p);
		session.removeAttribute(Person.SELECTED);
        return mapping.getInputForward();
    }

    protected ActionForward modeUnlinkPeople(ActionMapping mapping,
        ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
		EditOrgForm eof = (EditOrgForm) form;

        if (eof.getUnlink_people_ids() == null)
            return mapping.getInputForward();
		HttpSession session = request.getSession();
		List people=(List)session.getAttribute(Organization.PEOPLE);
        for (int i = 0; i < eof.getUnlink_people_ids().length; i++)
            for (int j = 0; j < people.size(); j++) {
                Person p = (Person) people.get(j);

                if (p.getId() == eof.getUnlink_people_ids()[i])
				people.remove(p);
            }

        return mapping.getInputForward();
    }

    protected ActionForward modeDelete(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();

        HttpSession session = request.getSession();
        Organization o = (Organization) session.getAttribute(Organization.EDIT_TAG);

        if (o == null)
            return mapping.findForward("plslogin");

        if ((o.getId() != -1) &&
                !ar.canDo(request, Perms.OBJECT_SUBMIT, o.getId(),
                    Arbiter.ORG_TYPE))
            return mapping.findForward("norights");

        o.setViewLang(lang);

        //constraints will issue an error here if we have dependencies
        try {
            orgdb.delete(o.getId());
        } catch (SQLException e) {
            return mapping.findForward("cannotdel");
        }

        request.setAttribute("operation", "'organization delete'");

        return mapping.findForward("success");
    }
}
